import 'package:dio/dio.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:safetymonitor/app/components/custom_modele/captcha/block_puzzle_captcha.dart';
import 'package:safetymonitor/app/components/toast_widget.dart';
import 'package:safetymonitor/app/core/constans/storage.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/env/env.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/http/network_manger.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/core/utils/log_util.dart';
import 'package:safetymonitor/app/core/utils/network.dart';
import 'package:safetymonitor/app/core/utils/storage_util.dart';
import 'package:safetymonitor/app/core/utils/user_manager.dart';
import 'package:safetymonitor/app/data/entities/auth/login_entity.dart';
import 'package:safetymonitor/app/data/entities/auth/user_profile_entity.dart';
import 'package:safetymonitor/global.dart';
import 'package:safetymonitor/router/app_pages.dart';

class LoginController extends GetxController {
  /// 用户名
  TextEditingController userNameEditing = TextEditingController();

  /// 用户名
  TextEditingController passwordEditing = TextEditingController();

  /// 验证码
  TextEditingController verificationEditing = TextEditingController();

  /// 是否隐藏密码
  final isHidePassword = true.obs;

  /// 验证码图片
  final baseImageBase64 = ''.obs;

  /// UUID
  String uuid = '';

  @override
  void onInit() {
    super.onInit();
    if (!Global.isRelease) {
      userNameEditing.text = 'admin';
      passwordEditing.text = 'admin123';
    }
    checkNetworkType();
  }


  /// 点击隐藏密码
  void onHidePasswordChanged() {
    isHidePassword.value = !isHidePassword.value;
  }

  /// 获取验证码
  Future<void> onGetVerificationCode() async {
    final res = await HttpUtil()
        .generateGetRequest(Interface.getCaptchaImage)
        .execute(isShowLoading: false);
    res.onSuccess((result) {
      if (result.data != null) {
        baseImageBase64.value = result.data['img'] as String;
        uuid = result.data['uuid'] as String;
      }
    });
  }

  /// 登录
  Future<void> onLogin() async {
    if (userNameEditing.text.isEmpty) {
      AppToast.showError('请输入用户名');
      return;
    }
    if (passwordEditing.text.isEmpty) {
      AppToast.showError('请输入密码');
      return;
    }
    // if (verificationEditing.text.isEmpty) {
    //   AppToast.showError('请输入验证码');
    //   return;
    // }
    login();
  }

  /// 登录完跳转
  void goHome(List<LoginAppMenuCodes> appMenuCodes) {
    Get.offNamed(Routes.home,arguments: appMenuCodes);
    AppToast.showSuccess('登录成功');
    SmartDialog.dismiss();
  }

  /// 登录接口
  void login() async {
    UserManager.removeToken();
    SmartDialog.showLoading(backType: SmartBackType.block, msg: '登录中...');
    // final res = await HttpUtil().generatePostRequest<NewLoginEntity>(Interface.loginUrl, data: {
    final res = await HttpUtil()
        .generatePostRequest<LoginEntity>(Interface.appLogin, data: {
      'username': userNameEditing.text,
      'password': passwordEditing.text,
      // 'captchaVerification': verificationEditing.text,
      // 'uuid': uuid,
    }).execute(isShowLoading: false);
    res.onSuccess((result) async {
      // 保存token
      UserManager.saveToken('Bearer ${result.data!.accessToken}');
      UserManager.saveUserCompanyName(result.data!.companyInfo.companyName);
      UserManager.saveUserCompanyID(result.data!.companyInfo.companyId);
      UserManager.saveUsername(userNameEditing.text);
      UserManager.savePassword(passwordEditing.text);
      // UserManager.saveToken('Bearer 3f98008aca904869b412798d20596562');
      if (result.data != null) {
        // 获取用户信息 systemFlag，系统类型标识，1-安全 2-环保 3-二者都有
        final res2 = await HttpUtil().generateGetRequest<UserProfileEntity>(Interface.getUserProfile).execute(isShowLoading: false);
        if (res2.data != null) {
          UserManager.saveUser(res2.data!);
          goHome(result.data!.appMenuCodes);
        }
      } else {
        UserManager.removeToken();
        AppToast.showError('用户数据为空');
        SmartDialog.dismiss();
      }
    });

    res.onError((result) {
      SmartDialog.dismiss();
    });
  }

  /// 滑动验证
  void onSlideVerify() {
    Get.dialog(BlockPuzzleCaptchaPage(
      onSuccess: (String captchaVerification) async {
        UserManager.removeToken();
        final res = await HttpUtil().generatePostRequest<LoginEntity>(Interface.loginUrl, data: {
          'username': userNameEditing.text,
          'password': passwordEditing.text,
          'captchaVerification': captchaVerification,
        }).execute(isShowLoading: false);
        res.onSuccess((result) async {
          // 保存token
          UserManager.saveToken('Bearer ${result.data!.accessToken}');
          // UserManager.saveToken('Bearer 3f98008aca904869b412798d20596562');
          if (result.data != null) {
            // 获取用户信息
            final res2 = await HttpUtil().generateGetRequest<UserProfileEntity>(Interface.getUserProfile).execute(isShowLoading: false);
            if (res2.data != null) {
              UserManager.saveUser(res2.data!);
              // goHome();
            }
          } else {
            UserManager.removeToken();
            AppToast.showError('用户数据为空');
          }
        });
      },
      onFail: () {},
    ));
  }


  /// 检查网络类型
  void checkNetworkType() async {
    NetworkManager.checkNetworkType();
  }


}

